package com.dongyimai.oauth.controller;

import com.dongyimai.oauth.service.AuthService;
import com.dongyimai.oauth.util.AuthToken;
import com.dongyimai.oauth.util.CookieUtil;
import com.offcn.entity.Result;
import com.offcn.entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Value("${auth.clientId}")
    private String clientId;

    @Value("${auth.clientSecret}")
    private String clientSecret;

    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;

    @PostMapping("/login")
    public Result login(String username, String password, String from) {
        System.out.println(username + "" + password);
        if (StringUtils.isEmpty(username) && StringUtils.isEmpty(password)) {
            throw new RuntimeException("用户名密码不能空");
        }

        AuthToken authToken = authService.login(username, password, clientId, clientSecret);

        String accessToken = authToken.getAccessToken();

        saveCookie(accessToken, from);
//        //把令牌存放在 cokie中
//        Cookie cookie = new Cookie("Authorization", accessToken);
//        cookie.setDomain(cookieDomain);
//        cookie.setMaxAge(cookieMaxAge);
//
//        //添加到响应中
//        response.addCookie(cookie);

        return new Result(true, StatusCode.OK, "登录成功");
    }

    private void saveCookie(String accessToken, String from) {

        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getResponse();
        CookieUtil.addCookie(response, cookieDomain, "/", "Authorization", accessToken, cookieMaxAge, false);
        response.setHeader("Refresh","3;URL="+from);//3秒后刷新页面 访问新的地址 from
    }
}
